# -*- coding: utf-8 -*-
"""
历史记录标签页
显示和管理计算历史
"""

from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel, QTextEdit, 
                            QGroupBox, QTableWidget, QTableWidgetItem, QPushButton,
                            QHeaderView, QMessageBox, QFileDialog, QApplication,
                            QFrame, QSplitter)
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QFont
from typing import Dict

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))

from utils.history_manager import HistoryManager


class HistoryTab(QWidget):
    """历史记录标签页"""
    
    def __init__(self, history_manager=None):
        super().__init__()
        self.history_manager = history_manager or HistoryManager()
        self.init_ui()
        self.load_history_data()
    
    def init_ui(self):
        """初始化用户界面"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(25, 25, 25, 25)
        layout.setSpacing(20)
        
        # 顶部：统计信息卡片（横向排列）
        stats_cards = self.create_stats_cards()
        layout.addWidget(stats_cards)
        
        # 中间：历史记录表格
        history_group = self.create_history_group()
        layout.addWidget(history_group)
        
        # 底部：按钮区域
        button_group = self.create_button_group()
        layout.addWidget(button_group)
    
    def create_history_group(self):
        """创建历史记录区域"""
        group_box = QGroupBox("计算历史")
        group_box.setFont(QFont("Microsoft YaHei", 11, QFont.Bold))
        group_box.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                border: 2px solid #dee2e6;
                border-radius: 8px;
                margin-top: 10px;
                padding-top: 15px;
                background-color: #ffffff;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 15px;
                padding: 0 8px 0 8px;
                color: #495057;
                background-color: #ffffff;
            }
        """)
        
        layout = QVBoxLayout(group_box)
        layout.setContentsMargins(25, 30, 25, 25)
        layout.setSpacing(15)
        
        # 历史记录表格
        self.history_table = QTableWidget()
        self.history_table.setColumnCount(4)
        self.history_table.setHorizontalHeaderLabels(["时间", "类型", "输入", "结果"])
        
        # 设置表格样式
        self.history_table.setStyleSheet("""
            QTableWidget {
                border: 2px solid #e9ecef;
                border-radius: 10px;
                background-color: #ffffff;
                gridline-color: #f1f3f4;
                selection-background-color: #e8f4fd;
                font-size: 11px;
            }
            QTableWidget::item {
                padding: 12px 8px;
                border-bottom: 1px solid #f1f3f4;
                border-right: none;
            }
            QTableWidget::item:selected {
                background-color: #e8f4fd;
                color: #1976d2;
            }
            QTableWidget::item:hover {
                background-color: #f8f9fa;
            }
            QHeaderView::section {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #ffffff, stop:1 #f8f9fa);
                border: 1px solid #dee2e6;
                border-bottom: 2px solid #007bff;
                padding: 12px 8px;
                font-weight: bold;
                font-size: 12px;
                color: #495057;
            }
            QHeaderView::section:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #f8f9fa, stop:1 #e9ecef);
            }
        """)
        
        # 设置表格属性
        self.history_table.setAlternatingRowColors(True)
        self.history_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.history_table.horizontalHeader().setStretchLastSection(True)
        self.history_table.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
        
        # 隐藏行号列（这就是显示点的那一列）
        self.history_table.verticalHeader().setVisible(False)
        
        # 设置列宽
        self.history_table.setColumnWidth(0, 150)  # 时间
        self.history_table.setColumnWidth(1, 100)  # 类型
        self.history_table.setColumnWidth(2, 200)  # 输入
        
        layout.addWidget(self.history_table)
        
        return group_box
    
    def create_stats_cards(self):
        """创建统计信息卡片"""
        frame = QFrame()
        frame.setMaximumHeight(120)
        layout = QHBoxLayout(frame)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(15)
        
        # 总计算次数卡片
        self.total_card = self.create_stat_card("📊", "总计算", "0", "#007bff")
        layout.addWidget(self.total_card)
        
        # 日期计算卡片
        self.date_card = self.create_stat_card("📅", "日期计算", "0", "#28a745")
        layout.addWidget(self.date_card)
        
        # 时间计算卡片
        self.time_card = self.create_stat_card("⏰", "时间计算", "0", "#17a2b8")
        layout.addWidget(self.time_card)
        
        # 农历转换卡片
        self.lunar_card = self.create_stat_card("🌙", "农历转换", "0", "#ffc107")
        layout.addWidget(self.lunar_card)
        
        return frame
    
    def create_stat_card(self, icon, title, value, color):
        """创建单个统计卡片"""
        card = QFrame()
        card.setFixedHeight(100)
        card.setStyleSheet(f"""
            QFrame {{
                background-color: #ffffff;
                border: 2px solid #e9ecef;
                border-radius: 12px;
                border-left: 4px solid {color};
            }}
            QFrame:hover {{
                border: 2px solid {color};
            }}
        """)
        
        layout = QVBoxLayout(card)
        layout.setContentsMargins(20, 15, 20, 15)
        layout.setSpacing(8)
        
        # 图标和标题行
        header_layout = QHBoxLayout()
        header_layout.setSpacing(10)
        
        # 图标
        icon_label = QLabel(icon)
        icon_label.setStyleSheet(f"""
            QLabel {{
                font-size: 20px;
                color: {color};
                background: transparent;
                border: none;
            }}
        """)
        icon_label.setFixedSize(30, 30)
        icon_label.setAlignment(Qt.AlignCenter)
        
        # 标题
        title_label = QLabel(title)
        title_label.setStyleSheet("""
            QLabel {
                font-size: 12px;
                font-weight: bold;
                color: #6c757d;
                background: transparent;
                border: none;
            }
        """)
        
        header_layout.addWidget(icon_label)
        header_layout.addWidget(title_label)
        header_layout.addStretch()
        
        # 数值
        value_label = QLabel(value)
        value_label.setStyleSheet(f"""
            QLabel {{
                font-size: 24px;
                font-weight: bold;
                color: {color};
                background: transparent;
                border: none;
            }}
        """)
        value_label.setAlignment(Qt.AlignLeft)
        
        layout.addLayout(header_layout)
        layout.addWidget(value_label)
        layout.addStretch()
        
        # 保存值标签的引用以便更新
        setattr(card, 'value_label', value_label)
        
        return card
    
    def create_button_group(self):
        """创建按钮区域"""
        frame = QFrame()
        frame.setMinimumHeight(70)
        frame.setStyleSheet("""
            QFrame {
                background-color: #f8f9fa;
                border-radius: 12px;
                border: 1px solid #e9ecef;
            }
        """)
        layout = QHBoxLayout(frame)
        layout.setSpacing(15)
        layout.setContentsMargins(25, 15, 25, 15)
        
        # 刷新按钮
        refresh_btn = QPushButton("🔄 刷新")
        refresh_btn.setMinimumHeight(45)
        refresh_btn.setMinimumWidth(100)
        refresh_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #007bff, stop:1 #0056b3);
                color: white;
                border: none;
                border-radius: 8px;
                font-size: 13px;
                font-weight: bold;
                padding: 10px 20px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #0056b3, stop:1 #004085);
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #004085, stop:1 #002752);
            }
        """)
        refresh_btn.clicked.connect(self.refresh_history)
        layout.addWidget(refresh_btn)
        
        # 导出按钮
        export_btn = QPushButton("📤 导出")
        export_btn.setMinimumHeight(45)
        export_btn.setMinimumWidth(100)
        export_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #28a745, stop:1 #1e7e34);
                color: white;
                border: none;
                border-radius: 8px;
                font-size: 13px;
                font-weight: bold;
                padding: 10px 20px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #1e7e34, stop:1 #155724);
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #155724, stop:1 #0f3d1a);
            }
        """)
        export_btn.clicked.connect(self.export_history)
        layout.addWidget(export_btn)
        
        layout.addStretch()
        
        # 清空历史按钮
        clear_btn = QPushButton("🗑️ 清空历史")
        clear_btn.setMinimumHeight(45)
        clear_btn.setMinimumWidth(120)
        clear_btn.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #dc3545, stop:1 #c82333);
                color: white;
                border: none;
                border-radius: 8px;
                font-size: 13px;
                font-weight: bold;
                padding: 10px 20px;
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #c82333, stop:1 #a71e2a);
            }
            QPushButton:pressed {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #a71e2a, stop:1 #861e25);
            }
        """)
        clear_btn.clicked.connect(self.clear_history)
        layout.addWidget(clear_btn)
        
        return frame
    
    def load_history_data(self):
        """加载历史数据到表格"""
        try:
            history = self.history_manager.get_history()
            self.history_table.setRowCount(len(history))
            
            for row, record in enumerate(reversed(history)):  # 最新记录在前
                # 时间
                time_item = QTableWidgetItem(record['formatted_time'])
                self.history_table.setItem(row, 0, time_item)
                
                # 类型
                type_item = QTableWidgetItem(record['calc_type'])
                self.history_table.setItem(row, 1, type_item)
                
                # 输入（简化显示）
                input_summary = self._format_input_summary(record)
                input_item = QTableWidgetItem(input_summary)
                self.history_table.setItem(row, 2, input_item)
                
                # 结果（简化显示）
                result_summary = self._format_result_summary(record)
                result_item = QTableWidgetItem(result_summary)
                self.history_table.setItem(row, 3, result_item)
            
            # 更新统计信息
            self.update_statistics()
            
        except Exception as e:
            QMessageBox.critical(self, "加载错误", f"加载历史记录时出现错误:\n{str(e)}")
    
    def _format_input_summary(self, record: Dict) -> str:
        """格式化输入摘要"""
        try:
            calc_type = record['calc_type']
            input_data = record['input_data']
            
            if 'date' in calc_type.lower():
                base_date = input_data.get('base_date', '')
                amount = input_data.get('amount', 0)
                unit = input_data.get('unit', '')
                operation = input_data.get('operation', '')
                return f"{base_date} {operation}{amount}{unit}"
            elif 'time' in calc_type.lower():
                base_time = input_data.get('base_time', '')
                hours = input_data.get('hours', 0)
                minutes = input_data.get('minutes', 0)
                return f"{base_time} +{hours}h{minutes}m"
            else:
                return str(input_data)[:50] + "..." if len(str(input_data)) > 50 else str(input_data)
                
        except Exception:
            return "解析失败"
    
    def _format_result_summary(self, record: Dict) -> str:
        """格式化结果摘要"""
        try:
            result_data = record['result_data']
            
            if 'formatted_date' in result_data:
                return result_data['formatted_date']
            elif 'formatted_result' in result_data:
                return result_data['formatted_result']
            elif 'solar_formatted' in result_data:
                return result_data['solar_formatted']
            else:
                return str(result_data)[:50] + "..." if len(str(result_data)) > 50 else str(result_data)
                
        except Exception:
            return "解析失败"
    
    def update_statistics(self):
        """更新统计信息"""
        try:
            stats = self.history_manager.get_statistics()
            
            # 确保stats不为空且包含所有必要的键
            if not stats:
                stats = {
                    'total_calculations': 0,
                    'date_calculations': 0,
                    'time_calculations': 0,
                    'lunar_conversions': 0,
                    'most_used_function': '暂无',
                    'first_use': '暂无',
                    'last_use': '暂无'
                }
            
            # 更新卡片数值
            self.total_card.value_label.setText(f"{stats.get('total_calculations', 0)}")
            self.date_card.value_label.setText(f"{stats.get('date_calculations', 0)}")
            self.time_card.value_label.setText(f"{stats.get('time_calculations', 0)}")
            self.lunar_card.value_label.setText(f"{stats.get('lunar_conversions', 0)}")
            
        except Exception as e:
            # 显示默认值
            self.total_card.value_label.setText("0")
            self.date_card.value_label.setText("0") 
            self.time_card.value_label.setText("0")
            self.lunar_card.value_label.setText("0")
    
    def refresh_history(self):
        """刷新历史记录"""
        self.history_manager.load_history()
        self.load_history_data()
        self.show_floating_tip("🔄 刷新完成", "#007bff")
    
    def export_history(self):
        """导出历史记录"""
        try:
            # 生成默认文件名（包含当前日期时间）
            from datetime import datetime
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            default_filename = f"时间计算器历史记录_{timestamp}"
            
            file_path, selected_filter = QFileDialog.getSaveFileName(
                self, "导出历史记录", default_filename, 
                "Excel文件 (*.xlsx);;CSV文件 (*.csv);;JSON文件 (*.json);;文本文件 (*.txt);;所有文件 (*)")
            
            if file_path:
                success = False
                
                if selected_filter.startswith("Excel"):
                    success = self.export_to_excel(file_path)
                elif selected_filter.startswith("CSV"):
                    success = self.export_to_csv(file_path)
                elif selected_filter.startswith("JSON"):
                    success = self.history_manager.export_history(file_path)
                elif selected_filter.startswith("文本"):
                    success = self.export_to_text(file_path)
                else:
                    # 根据文件扩展名判断格式
                    ext = os.path.splitext(file_path)[1].lower()
                    if ext == '.xlsx':
                        success = self.export_to_excel(file_path)
                    elif ext == '.csv':
                        success = self.export_to_csv(file_path)
                    elif ext == '.txt':
                        success = self.export_to_text(file_path)
                    else:
                        success = self.history_manager.export_history(file_path)
                
                if success:
                    self.show_floating_tip("📤 导出成功", "#28a745")
                else:
                    QMessageBox.critical(self, "导出失败", "导出历史记录失败，请检查文件路径和权限。")
                    
        except Exception as e:
            QMessageBox.critical(self, "导出错误", f"导出过程中出现错误:\n{str(e)}")
    
    def export_to_excel(self, file_path: str) -> bool:
        """导出为Excel格式"""
        try:
            import pandas as pd
            
            # 准备数据
            data = []
            for record in self.history_manager.get_history():
                row = {
                    '时间': record['formatted_time'],
                    '类型': record['calc_type'],
                    '输入': self._format_input_summary(record),
                    '结果': self._format_result_summary(record)
                }
                data.append(row)
            
            # 创建DataFrame并导出
            df = pd.DataFrame(data)
            df.to_excel(file_path, index=False, sheet_name='计算历史')
            return True
            
        except ImportError:
            QMessageBox.warning(self, "缺少依赖", "导出Excel需要安装pandas和openpyxl库\n\n请运行: pip install pandas openpyxl")
            return False
        except Exception as e:
            print(f"导出Excel失败: {e}")
            return False
    
    def export_to_csv(self, file_path: str) -> bool:
        """导出为CSV格式"""
        try:
            import csv
            
            with open(file_path, 'w', newline='', encoding='utf-8-sig') as csvfile:
                writer = csv.writer(csvfile)
                
                # 写入标题行
                writer.writerow(['时间', '类型', '输入', '结果'])
                
                # 写入数据
                for record in self.history_manager.get_history():
                    row = [
                        record['formatted_time'],
                        record['calc_type'],
                        self._format_input_summary(record),
                        self._format_result_summary(record)
                    ]
                    writer.writerow(row)
            
            return True
            
        except Exception as e:
            print(f"导出CSV失败: {e}")
            return False
    
    def export_to_text(self, file_path: str) -> bool:
        """导出为文本格式"""
        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write("时间计算器 - 历史记录导出\n")
                f.write("=" * 50 + "\n\n")
                
                for i, record in enumerate(self.history_manager.get_history(), 1):
                    f.write(f"记录 {i}:\n")
                    f.write(f"时间: {record['formatted_time']}\n")
                    f.write(f"类型: {record['calc_type']}\n")
                    f.write(f"输入: {self._format_input_summary(record)}\n")
                    f.write(f"结果: {self._format_result_summary(record)}\n")
                    f.write("-" * 30 + "\n\n")
                
                # 添加统计信息
                stats = self.history_manager.get_statistics()
                f.write("使用统计:\n")
                f.write(f"总计算次数: {stats.get('total_calculations', 0)}次\n")
                f.write(f"日期计算: {stats.get('date_calculations', 0)}次\n")
                f.write(f"时间计算: {stats.get('time_calculations', 0)}次\n")
                f.write(f"农历转换: {stats.get('lunar_conversions', 0)}次\n")
                f.write(f"最常用功能: {stats.get('most_used_function', '暂无')}\n")
            
            return True
            
        except Exception as e:
            print(f"导出文本失败: {e}")
            return False
    
    
    def clear_history(self):
        """清空历史记录"""
        reply = QMessageBox.question(self, "确认清空", 
                                   "确定要清空所有历史记录吗？\n\n此操作不可恢复！",
                                   QMessageBox.Yes | QMessageBox.No,
                                   QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            self.history_manager.clear_history()
            self.load_history_data()
            self.show_floating_tip("🗑️ 清空完成", "#dc3545")
    
    def show_floating_tip(self, message, color):
        """显示浮动提示"""
        from PyQt5.QtCore import QTimer
        from PyQt5.QtWidgets import QFrame
        
        # 创建卡片式提示框
        tip_frame = QFrame(self)
        tip_frame.setFrameStyle(QFrame.NoFrame)
        
        # 根据颜色设置背景
        if color == "#28a745":  # 绿色
            bg_color = "rgba(212, 237, 218, 0.95)"
            border_color = "rgba(40, 167, 69, 0.3)"
            text_color = "#155724"
        elif color == "#007bff":  # 蓝色
            bg_color = "rgba(204, 229, 255, 0.95)"
            border_color = "rgba(0, 123, 255, 0.3)"
            text_color = "#004085"
        elif color == "#17a2b8":  # 青色
            bg_color = "rgba(209, 236, 241, 0.95)"
            border_color = "rgba(23, 162, 184, 0.3)"
            text_color = "#0c5460"
        else:  # 红色
            bg_color = "rgba(248, 215, 218, 0.95)"
            border_color = "rgba(220, 53, 69, 0.3)"
            text_color = "#721c24"
        
        tip_frame.setStyleSheet(f"""
            QFrame {{
                background-color: {bg_color};
                border: 1px solid {border_color};
                border-radius: 12px;
            }}
        """)
        
        # 创建布局
        layout = QHBoxLayout(tip_frame)
        layout.setContentsMargins(16, 12, 16, 12)
        layout.setSpacing(12)
        
        # 创建圆形图标
        icon_label = QLabel("✓", tip_frame)
        icon_label.setStyleSheet(f"""
            QLabel {{
                background-color: {color};
                color: white;
                border-radius: 15px;
                font-size: 14px;
                font-weight: bold;
                min-width: 30px;
                max-width: 30px;
                min-height: 30px;
                max-height: 30px;
            }}
        """)
        icon_label.setAlignment(Qt.AlignCenter)
        
        # 创建文字标签
        text_label = QLabel(message.split(' ', 1)[1] if ' ' in message else message, tip_frame)
        text_label.setStyleSheet(f"""
            QLabel {{
                color: {text_color};
                font-size: 14px;
                font-weight: bold;
                background: transparent;
                border: none;
            }}
        """)
        
        layout.addWidget(icon_label)
        layout.addWidget(text_label)
        
        # 调整框架大小
        tip_frame.adjustSize()
        tip_frame.setFixedSize(tip_frame.sizeHint())
        
        # 定位在应用的上半部分中央
        parent_rect = self.rect()
        tip_x = (parent_rect.width() - tip_frame.width()) // 2
        tip_y = parent_rect.height() // 6  # 放在上1/6位置
        tip_frame.move(tip_x, tip_y)
        
        # 显示提示框
        tip_frame.show()
        tip_frame.raise_()  # 确保在最顶层
        
        # 2秒后自动消失
        QTimer.singleShot(2000, tip_frame.deleteLater)
    
    def add_calculation_to_history(self, calc_type: str, input_data: Dict, result_data: Dict):
        """添加计算记录到历史"""
        self.history_manager.add_calculation_record(calc_type, input_data, result_data)
        self.load_history_data()
    
    def clear_inputs(self):
        """清空输入"""
        pass
    
    def copy_result(self):
        """复制结果"""
        current_row = self.history_table.currentRow()
        if current_row >= 0:
            # 复制选中行的信息
            time_text = self.history_table.item(current_row, 0).text()
            type_text = self.history_table.item(current_row, 1).text()
            input_text = self.history_table.item(current_row, 2).text()
            result_text = self.history_table.item(current_row, 3).text()
            
            clipboard_text = f"时间: {time_text}\n类型: {type_text}\n输入: {input_text}\n结果: {result_text}"
            
            clipboard = QApplication.clipboard()
            clipboard.setText(clipboard_text)
            
            self.show_floating_tip("📋 复制成功", "#28a745")
        else:
            QMessageBox.warning(self, "提示", "请先选择要复制的历史记录")
    
    def clear_all(self):
        """清空所有内容"""
        self.clear_history()
